package org.itli.jnsocket.Controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.itli.jnsocket.Pojo.GoodsCategory;
import org.itli.jnsocket.Result.Result;
import org.itli.jnsocket.Service.GoodsService;
import org.itli.jnsocket.Util.JWTUtil;
import org.itli.jnsocket.VTO.GoodCatrgory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Slf4j
@Tag(name="商品分类接口")
@RequestMapping("/Goods")
@RestController
public class GoodsController {

    GoodsService service;

    JWTUtil jwt = new JWTUtil();

    @Autowired
    public void setService(GoodsService service) {
        this.service = service;
    }

    //获取所有分类
    @GetMapping("/AllCategory")
    @Operation(summary = "获取所有分类")
    public Result<String> AllCategory(){
        String s = service.AllCatrgory();
        log.info(s);
        return Result.success(s);
    }

    //新增分类
    @PostMapping("/AddPCategory")
    @Operation(summary = "添加父分类")
    public Result<String> AddPCategory(@RequestHeader("Authorization") String token, @RequestBody GoodCatrgory newCategory){
        log.info("请求到添加分类");
        Map<String, Object> cliam;
        try{
            cliam = jwt.parseToken(token);
        } catch (Exception e) {
            return Result.success("令牌过期");
        }
        String username = (String) cliam.get("username");
        log.info("获取到用户名"+username);
        String s = service.newCategory(username,newCategory.getName(),newCategory.getWeight());
        return Result.success(s);
    }

    //新增子分类
    @PostMapping("/AddSubCategory")
    @Operation(summary = "添加子分类")
    public Result<String> AddSubCategory(@RequestHeader("Authorization") String token, @RequestBody GoodCatrgory newCategory){
        Map<String, Object> cliam;
        try{
            cliam = jwt.parseToken(token);
        } catch (Exception e) {
            return Result.success("令牌过期");
        }
        String username = (String) cliam.get("username");
        String s = service.AddSubCategory(newCategory, username);
        return Result.success(s);
    }

    //删除分类
    @PostMapping("/DeleteCategory")
    @Operation(summary = "删除分类")
    public Result<String> DeleteCategory(@RequestBody GoodCatrgory newCategory){
        String s = service.DeleteCategory(newCategory.getName());
        return Result.success(s);
    }
}
